/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: BehaviourClientExample.cpp,v 1.7 2009-10-26 12:48:36 morsko Exp $
 *
 * \file
 * \brief This is an example for using the Behaviour interface.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */
#include "BehaviourClient.hpp"

//*****************************************************************************
#define GIMI_CLIENT_API 20000
#include "gimi.h"
//*****************************************************************************
using namespace MaCI::Behaviour;
//*****************************************************************************
static int verbose = 1;
//*****************************************************************************
static gimi::GIMI g;
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tBehaviourClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tUse 'name' as Behaviour target\n");
  fprintf(stderr,"  \t\t\t\tOR\n");
  fprintf(stderr,"  [-S name]\t\t\tSpecify the data source by MaCISL\n\n");
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      dPrint(1,"Terminating...");
      run = false;
      /* g.stop();
      dPrint(1,"Waiting 3 seconds for cleanup...");
      ownSleep_ms(2000);
      dPrint(1,"Exit.");
      ownSleep_ms(1000);
      exit(1); // Force :)*/
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
int main(int argc, char *argv[]) 
{
  
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName = "";
  std::string gimnetSourceName = "";
  std::string datasourceMaCISL;
  // Objects
  MaCI::Behaviour::CBehaviourClient bc(&g, 0);

 // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(3);
  debugSetLogFilename("BehaviourClientExample.log");

  // InitSignalHandler
  InitSignalHandler();

  // Greet
  fprintf(stderr,
	  "\nBehaviourClientExample - MaCI Behaviour Interface Example - v0.0\n");

  // Parse parameters
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "s:S:n:u:p:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////
      ///// GIMnet parameters /////////
      /////////////////////////////////
    case 's':
      gimnetSourceName = optarg;
      dPrint(3,"Using GIMnet source name '%s'", optarg);
      break;

    case 'S':
      datasourceMaCISL = optarg;
      dPrint(3,"Using DataSource MaCISL '%s'", optarg);
      break;
    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }

  MaCI::EMaCIError e;
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());



    // Assign default target.
    if (gimnetSourceName.size()) {
      bc.SetDefaultTarget(gimnetSourceName);
      
    } else {
      // GIMI is Open(), so we can execute this.
      MaCI::MaCICtrl::SMaCISL sl(datasourceMaCISL);
      if (sl.IsValidFQMaCISL()) {
        bc.SetDefaultTarget(sl, 10000);
      }
    
    }
    // Attempt to Open Client
    if ( (e = bc.Open()) != MaCI::KMaCIOK) {
      dPrint(1,"Failed to Open BehaviourClient instance! (%s)",
	     GetErrorStr(e).c_str());
      
    } else {
      const int timeout = 1000;
      CBehaviourData behaviourData;
      bool dataAvailable;
      int sequence = -1;
      dPrint(1,"Let's ask for behaviour info");
      TBehaviourInformation info;
      if(bc.GetBehaviourInfo(info,timeout)){
        dPrint(1,"Behaviour type %d",info.type);
      }else{
        dPrint(1,"Failed to get behaviour information");
      }

      while(run) {
	dPrint(1,"Trying to get Event, using for timeout %d ms", timeout);
	dataAvailable = bc.GetBehaviourControlEvent(behaviourData, &sequence, timeout);

        if(dataAvailable){
	  dPrint(1,"Got Data! Printing its contents:");
	  behaviourData.Print(1);
	}else{
	  dPrint(1,"No data :(");

	}
        
        if(bc.SetStart()){
          dPrint(1,"Set start called succesfully");
          ownSleep_ms(500);
        }


        dPrint(1,"Get server state");
        
        dPrint(1,"State is %d", bc.GetBehaviourState());
        if(bc.SetStop()){
          dPrint(1,"Set stop called succesfully");
          ownSleep_ms(500);
        }
        dPrint(1,"State is %d", bc.GetBehaviourState());
      }
      
    }
  }
  bc.Close();
  return 0;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

